<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * 聊友记录
 */
class UserChat extends Model
{
    protected $table = 'user_chat';

    //个人主页
    const FROM_MAIN_PAGE = 1;
    //首页-一键搭讪
    const FROM_QUICK_CHAT = 3;
    //上线提醒
    const FROM_ONLINE_TIP = 2;
    //IOS提审版-上线用户推荐卡
    const FROM_REC_USER_CARD = 4;
    //IOS提审版-缘分匹配
    const FROM_MATCH = 5;
    //首页用户列表
    const FROM_USER_LIST = 6;
    //动态列表
    const FROM_MOMENT_LIST = 7;

    protected $fillable = [
        'user_id', 'chat_user_id', 'flag', 'msg_num', 'chat_msg_num', 'from'
    ];

    /**
     * 检测记录
     */
    static function check($userId = 0, $chatUserId = 0, $startTime = '')
    {
        $where = [
            ['user_id', $userId],
            ['chat_user_id', $chatUserId]
        ];
        $startTime && $where[] = ['created_at', '>', $startTime];
        $orWhere = [
            ['chat_user_id', $userId],
            ['user_id', $chatUserId]
        ];
        $startTime && $orWhere[] = ['created_at', '>', $startTime];
        return self::where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->first();
    }

    /**
     * 插入聊友记录
     */
    static function addRecord($userId = 0, $chatUserId = 0, $from = self::FROM_MAIN_PAGE,$startTime = '')
    {
        if ($item = self::check($userId, $chatUserId,$startTime)) return false; //$item->toArray();
        return self::create([
            'user_id' => $userId,
            'chat_user_id' => $chatUserId,
            'flag' => 1,
            'from' => $from
        ]);
    }

    /**
     * 更新聊天数量
     */
    static function updateMsgNum($userId = 0, $chatUserId = 0, $msgNum = 1)
    {
        $record = self::check($userId, $chatUserId);
        if (!$record) {
            $record = new self();
            $record->user_id = $userId;
            $record->chat_user_id = $chatUserId;
            $record->msg_num = $msgNum;
            $record->saveOrFail();
        } else {
            $field = $record->user_id == $userId ? 'msg_num' : 'chat_msg_num';
            self::where('id', $record->id)->increment($field, $msgNum);
            $record->{$field} += $msgNum;
        }
        return $record;
    }

    /**
     * 今天开启的聊天次数
     */
    static function checkToday($userId = 0, $start = '', $end = '')
    {
        $start = $start ?: date('Y-m-d');
        $where = [
            ['user_id', $userId],
            ['msg_num', '>', 0],
            ['chat_msg_num', '>', 0],
            ['created_at', '>', $start]
        ];
        $end && $where[] = ['created_at', '<', $end];
        return self::where($where)->count();
    }

    /**
     * 今天开启的招呼数
     */
    static function checkTodayShouye($userId = 0, $start = '', $end = '')
    {
        $start = $start ?: date('Y-m-d');
        $from = 6;
        $flag = 1;
        $where = [
            ['user_id', $userId],
            ['from', $from],
            ['flag', $flag],
            ['created_at', '>', $start]
        ];
        $end && $where[] = ['created_at', '<', $end];
        return self::where($where)->count();
    }

    /**
     * 查当前用户聊天记录
     */
    static function pickMsgNum(UserChat $userChat = null, $curUserId = 0)
    {
        if (!$userChat) return 0;
        return $userChat->user_id == $curUserId ? $userChat->msg_num : $userChat->chat_msg_num;
    }

    /**
     * 选出聊天对象ID
     */
    static function pickChatUserId(UserChat $userChat = null, $curUserId = 0)
    {
        if (!$userChat) return 0;
        return $userChat->user_id == $curUserId ? $userChat->chat_user_id : $userChat->user_id;
    }

    /**
     * 开启聊天（根据入口）
     */
    static function checkStartFrom($userId = 0, $from = 1)
    {
        $where = [
            'user_id' => $userId,
            'from' => $from
        ];
        return self::where($where)->count();
    }

    /**
     * 消息回复
     */
    static function checkMsgBack($userId = 0)
    {
        $where = [
            ['chat_user_id', $userId],
            ['chat_msg_num', '>', 0],
        ];
        $orWhere = [
            ['user_id', $userId],
            ['msg_num', '>', 0],
        ];
        return self::where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->count();
    }

    /**
     * 获取一段时间内交互过的用户ID
     */
    static function getMsgUserIds($userId, $offTime = 600)
    {
        $endTime = time() - $offTime;
        $where = [['user_id', $userId]];
        $orWhere = [['chat_user_id', $userId]];
        $cond = [
            ['msg_num', '>', 0],
            ['chat_msg_num', '>', 0],
            ['updated_at', '>', date('Y-m-d H:i:s', $endTime)],
        ];
        $where = array_merge($where, $cond);
        $orWhere = array_merge($orWhere, $cond);
        $items = UserChat::where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->select(['user_id', 'chat_user_id'])->get()->toArray();
        $uids = [];
        foreach ($items as $item) $uids[] = $userId == $item['user_id'] ? $item['chat_user_id'] : $item['user_id'];
        return $uids;
    }

    /**
     * 一键搭讪记录
     */
    static function getMsgUserById($userId,$hostId,$type= self::FROM_QUICK_CHAT ,$offTime=86400)
    {
        $endTime = time() - $offTime;
        $ret = UserChat::where('user_id',$userId)
            ->where('chat_user_id',$hostId)
            ->where('from',$type)
            ->where('updated_at','>',date('Y-m-d H:i:s', $endTime))
            ->first();
        return empty($ret) ? 1 : 0;
    }
}
